package com.xrtn.service.impl;

import com.xrtn.bean.*;
import com.xrtn.mapper.*;
import com.xrtn.page.Page;
import com.xrtn.service.ISysOrderService;
import com.xrtn.utils.*;
import io.netty.util.internal.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.*;

/**
 * Created by tu_pei on 2018/3/9.
 */
@Service
public class SysOrderServiceImpl implements ISysOrderService{

    @Autowired
    private TOrderInfoMapper orderInfoMapper;
    @Autowired
    private TUserInfoMapper userInfoMapper;
    @Autowired
    private SysUserInfoMapper sysUserInfoMapper;
    @Autowired
    private TCouponUsrRelMapper couponUsrRelMapper;
    @Autowired
    private TPatientTreatmentMapper treatmentMapper;
    /**
     * 用户次卡消费记录表
     */
    @Autowired
    private TCardUsrRelMapper cardUsrRelMapper;
    @Autowired
    private TOrderGoodsDetailMapper orderGoodsDetailMapper;
    @Autowired
    private TOrderServiceDetailMapper orderServiceDetailMapper;
    /**
     * 用户消费流水
     */
    @Autowired
    private AccountUserInfoMapper accountUserInfoMapper;
    /**
     * 医生提成流水
     */
    @Autowired
    private AccountDoctorInfoMapper accountDoctorInfoMapper;
    /**
     * 订单流水
     */
    @Autowired
    private AccountOrderInfoMapper accountOrderInfoMapper;

    @Autowired
    private SysAccountCardInfoMapper sysAccountCardInfoMapper;
    @Autowired
    private SysDiscountCardInfoMapper sysDiscountCardInfoMapper;

    @Autowired
    private TBookingInfoMapper bookingInfoMapper;

    @Autowired
    private TSubclinicInfoMapper subclinicInfoMapper;

    @Autowired
    private TPatientInitMapper patientInitMapper;

    @Autowired
    private TDoctorPushRelMapper doctorPushRelMapper;

    @Autowired

    private TPatientTreatmentMapper patientTreatmentMapper;
    @Autowired
    private TBackcardInfoMapper backcardInfoMapper;
    @Autowired
    private InitServiceInfoMapper serviceInfoMapper;
    @Autowired
    private SysRoleInfoMapper roleInfoMapper;


    @Override
    public Page selectOrderList(Page page,Map<String, Object> params) {

        Object dayType = params.get("dayType");

        Integer orderType = null; // 就诊单还是商品单 模拟数据，1:就诊单； 2：商品单
        if(ObjUtils.isNotEmpty(params.get("payWay"))){
            Integer payWay = (Integer) params.get("payWay");
            orderType = payWay == 6 ? 2 : 1;
        } else {
            orderType = 1;
        }
        params.put("orderType", orderType);


        if(ObjUtils.isNotEmpty(dayType)){

            if(dayType.toString().equals("1")){
                //今天
                params.put("startDate",new Date());
                params.put("endDate",null);
            }
            if(dayType.toString().equals("2")){
                //近3天
                params.put("startDate", DateUtils.addDay(new Date(),-3));
            }
            if(dayType.toString().equals("3")){
                //近7天
                params.put("startDate", DateUtils.addDay(new Date(),-7));
            }
        }



        if(ObjUtils.isEmpty(params.get("page"))){

            List<Map<String,Object>> list = orderInfoMapper.selectSysOrderPageList(page,params);

            for (Map<String,Object> map : list){
                params.put("bookingId", map.get("bookingId"));
                params.put("old", 1);//最近一条病例
                TPatientTreatment patientTreatment = patientTreatmentMapper.selectByMap(params);
                if(ObjUtils.isNotEmpty(patientTreatment)){
                    map.put("treatmentId", patientTreatment.getTreatmentId());
                }else{
                    map.put("treatmentId", null);
                }
            }
            page.setItems(list);
        }else{
            List<Map<String, Object>> total = orderInfoMapper.selectSysOrderPageTotal(params);
            page.setTotalRecord(total.size());
            params.put("offset", (page.getPageNo() - 1) * page.getPageSize());
            params.put("pageSize", page.getPageSize());
            page.setItems(orderInfoMapper.selectSysOrderPageOffsetLists(params));

//            page.setItems(orderInfoMapper.selectSysOrderPageLists(page, params));
        }


        return page;
    }

    /**
     * 绩效分页
     *
     * @param page
     * @param params
     * @return
     */
    @Override
    public Page selectOrderSaleList(Page page, Map<String, Object> params) {
        List<Map<String,Object>> list = orderInfoMapper.selectSysOrderSalePageList(page,params);
        page.setItems(list);
        return page;
    }

    /**
     * 查询订单详情
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> selectOrderInfo(Map<String, Object> params) {

        if(ObjUtils.isEmpty(params.get("orderType"))){
            return null;
        }

        Map<String,Object> retMap = new HashMap<>();

        Integer orderType = Integer.parseInt(params.get("orderType").toString());

        if(orderType == 0){

            TOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(Integer.parseInt(params.get("orderId").toString()));

            if(ObjUtils.isEmpty(orderInfo)){
                params = null;
                return params;
            }

            TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(orderInfo.getUserId());

            List<TOrderGoodsDetail> goodsList = orderGoodsDetailMapper.selectByMap(params);
            params.put("userId", orderInfo.getUserId());
            List<TOrderServiceDetail> serviceList = orderServiceDetailMapper.selectByMap(params);

            List<SysAccountCardInfo> cardList = new ArrayList<>();

            if(ObjUtils.isNotEmpty(orderInfo.getCardId())){
                String[] cardId = orderInfo.getCardId().split(",");
                for (String card : cardId){
                    params.put("cardId", card);
                    params.put("cardType", 5);
                    List<SysAccountCardInfo> accountCardList = sysAccountCardInfoMapper.selectByMap(params);
                    for (SysAccountCardInfo cardInfo : accountCardList){
                        for (TOrderServiceDetail service : serviceList){
                            if(cardInfo.getServiceId() == service.getServiceId()){
                                //标示哪些服务是使用了计次卡
                                service.setIsUse(1);
                            }
                        }
                    }
                    SysAccountCardInfo cardInfo = sysAccountCardInfoMapper.selectByPrimaryKey(Integer.parseInt(card));
                    if(ObjUtils.isNotEmpty(cardInfo)){
                        //返回本次订单所有使用的计次卡列表
                        cardList.add(cardInfo);
                    }
                }
            }else {
                for (TOrderServiceDetail service : serviceList){
                    service.setIsUse(0);
                }
            }
            SysDiscountCardInfo discountCardInfo = new SysDiscountCardInfo();
            if(ObjUtils.isNotEmpty(orderInfo.getCouponId())){
                //本次订单所使用的优惠券信息
                discountCardInfo = sysDiscountCardInfoMapper.selectByPrimaryKey(orderInfo.getCouponId());

                if(ObjUtils.isNotEmpty(discountCardInfo.getServiceId())){
                    InitServiceInfo serviceInfo = serviceInfoMapper.selectByPrimaryKey(discountCardInfo.getServiceId());
                    if(ObjUtils.isNotEmpty(serviceInfo)){
                        discountCardInfo.setServiceName(serviceInfo.getServiceName());
                    }
                }

            }

            SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(orderInfo.getDoctorId());

            if(ObjUtils.isNotEmpty(sysUserInfo)){
                orderInfo.setDoctorName(sysUserInfo.getUserName());
            }else{
                sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(orderInfo.getCashierId());

                if(ObjUtils.isNotEmpty(sysUserInfo)){
                    orderInfo.setDoctorName(sysUserInfo.getUserName());
                }
            }
            TUserInfo payUser = new TUserInfo();
            if(ObjUtils.isNotEmpty(orderInfo.getPayUserId())){
                payUser = userInfoMapper.selectByPrimaryKey(orderInfo.getPayUserId());
                orderInfo.setPayUserName(payUser.getUserName());
                orderInfo.setPayUserPhone(payUser.getUserPhone());
            }


            retMap.put("cardInfo",discountCardInfo);
            retMap.put("cardList", cardList);
            retMap.put("orderInfo",orderInfo);
            retMap.put("userInfo",userInfo);
            retMap.put("goodsList",goodsList);
            retMap.put("serviceList",serviceList);
        }else{

            //保持和订单详情返回数据一致，因为两块公用一个接口

            AccountUserInfo orderInfo = accountUserInfoMapper.selectByPrimaryKey(Integer.parseInt(params.get("orderId").toString()));

            //新增开卡备注字段
            params.put("accountId", orderInfo.getAccountId());
            List<TCardUsrRel> usrRelList = cardUsrRelMapper.selectByMap(params);
            if( usrRelList.size() > 0 ){
                orderInfo.setCardDesc(usrRelList.get(0).getCardDesc());
            }

            orderInfo.setOrderTime(orderInfo.getCreateTime());

            TSubclinicInfo subclinicInfo = subclinicInfoMapper.selectByPrimaryKey(orderInfo.getSubclinicId());

            if(ObjUtils.isNotEmpty(subclinicInfo)){
                orderInfo.setSubclinicName(subclinicInfo.getSubclinicName());
            }

            if(ObjUtils.isEmpty(orderInfo)){
                params = null;
                return params;
            }
            SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(orderInfo.getCashierId());

            if(ObjUtils.isNotEmpty(sysUserInfo)){
                orderInfo.setDoctorName(sysUserInfo.getUserName());
                orderInfo.setCashierName(sysUserInfo.getUserName());
            }

            TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(orderInfo.getUserId());
            // 查询消费具体服务项目 - 储值
            List<SysAccountCardInfo> serviceList = new ArrayList<>();
            SysAccountCardInfo service = sysAccountCardInfoMapper.selectByPrimaryKey(Integer.parseInt(orderInfo.getCardId()));

            serviceList.add(service);

            retMap.put("orderInfo",orderInfo);
            retMap.put("userInfo",userInfo);
            retMap.put("serviceList",serviceList);

            List<TOrderGoodsDetail> goodsList = new ArrayList<>();
            retMap.put("goodsList",goodsList);

        }
        return retMap;
    }

    @Override
    public TOrderInfo selectOrderInfoByBookingId(Map<String,Object> params) {
        return orderInfoMapper.selectByMap(params);
    }

    /**
     * 根据推拿服务id订单总价查询次卡和可用优惠券列表
     *
     * @param params
     * @return
     */
    @Override
    public Map<String, Object> selectUserCardList(Map<String, Object> params) {

        List<Map<String,Object>> cardList = cardUsrRelMapper.selectCardLeftTimeSum(params);

        params.put("isUsed", 0);
        List<Map<String,Object>> couponList = couponUsrRelMapper.selectByMap(params);

        Map<String,Object> retMap = new HashMap<>();
        retMap.put("cardList",cardList);
        retMap.put("couponList",couponList);

        return retMap;
    }

    /**
     * 修改订单
     *
     * @param orderInfo
     * @return
     */
    @Override
    public Integer updateOrderInfo(TOrderInfo orderInfo) {
        return orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
    }

    /**
     * 修改订单
     *
     * @param params
     * @return
     */
    @Override
    public ResponseData updateOrderInfo(Map<String, Object> params, ResponseData data) {

        String userPhone = params.get("userPhone").toString();

        String code = NumberUtils.generatorNumber(6);

        Integer orderId = Integer.parseInt(params.get("orderId").toString());

        TOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);

        int userId = 0;
        if(ObjUtils.isEmpty(orderInfo)){
            data.setCodeEnum(CodeEnum.CODE_60023);
            return data;
        }

        if(orderInfo.getOrderState() == 0 ){
            data.setCodeEnum(CodeEnum.CODE_60006);
            return data;
        }

        orderInfo.setReplacePayCode(code);
        orderInfo.setPayUserPhone(userPhone);
        Date now = new Date();
        Date afterDate = new Date(now .getTime() + 600000);

        orderInfo.setPayCreateTime(afterDate);

        BigDecimal userAccount = new BigDecimal(0);

        List<TUserInfo> userInfo = userInfoMapper.selectByMap(params);
        if(userInfo.size() > 0){
            userAccount = userInfo.get(0).getUserAccount();
            userId = userInfo.get(0).getUserId();
        } else {
            data.setCodeEnum(CodeEnum.CODE_10003);
            return data;
        }
        int payUserId = orderInfo.getUserId();
        if( userId == payUserId){
            data.setCodeEnum(CodeEnum.CODE_10014);
            return data;
        }
        if(userAccount.intValue() < orderInfo.getOrderPayCost().intValue()){
            data.setCodeEnum(CodeEnum.CODE_60008);
            return data;
        }

        orderInfoMapper.updateByPrimaryKeySelective(orderInfo);

        //发送验证码
        SendValidataCode.sendSms(userPhone, "238271" , code);

        return data;
    }

    /**
     * 修改订单
     *
     * @param orderId
     * @param code
     * @return
     */
    @Override
    public ResponseData updatePayOrder(Integer orderId, String userPhone, String code, ResponseData data) {

        TOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);

        if(ObjUtils.isEmpty(orderInfo)){
            data.setCodeEnum(CodeEnum.CODE_60023);
            return data;
        }
        if(orderInfo.getOrderState() == 0 ){
            data.setCodeEnum(CodeEnum.CODE_60006);
            return data;
        }

        Map<String,Object> params = new HashMap<>();
        params.put("userPhone", userPhone);

        List<TUserInfo> userInfo = userInfoMapper.selectByMap(params);
        if(userInfo.size() > 0){
            orderInfo.setPayUserId(userInfo.get(0).getUserId());

            data.setResults(userInfo.get(0));

            if(userInfo.get(0).getUserAccount().intValue() < orderInfo.getOrderPayCost().intValue()){
                data.setCodeEnum(CodeEnum.CODE_60008);
                return data;
            }
        }else{
            data.setCodeEnum(CodeEnum.CODE_10003);
            return data;
        }

        if(!code.equals(orderInfo.getReplacePayCode())){
            data.setCodeEnum(CodeEnum.CODE_10001);
            return data;
        }

        //orderInfoMapper.updateByPrimaryKeySelective(orderInfo);

        return data;
    }

    /**
     * 取消代付
     *
     * @param orderId
     * @param data
     * @return
     */
    @Override
    public ResponseData updateOtherPayOrderInfo(Integer orderId, ResponseData data) {

        TOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);

        if(ObjUtils.isEmpty(orderInfo)){
            data.setCodeEnum(CodeEnum.CODE_60023);
            return data;
        }

        orderInfo.setPayUserId(null);
        orderInfo.setReplacePayCode(null);
        orderInfoMapper.updateOtherPayUser(orderInfo);

        return data;
    }


    /**
     * 提交订单
     *
     * @param params
     * @return
     */

    @Override
    public ResponseData saveOrderInfo(Map<String, Object> params) throws Exception{
        ResponseData data = new ResponseData();

           try{
               Integer orderId = Integer.parseInt(params.get("orderId").toString());

               Integer cashierId = Integer.parseInt(params.get("cashierId").toString());

               //校验收银人员是否有收银权限
               boolean isPay = false;
               if(ObjUtils.isNotEmpty(cashierId)){
                   SysUserInfo sysUserInfo = sysUserInfoMapper.selectByPrimaryKey(cashierId);
                   List<Map<String,Object>> userFunctionList= roleInfoMapper.selectRoleLists(sysUserInfo.getUserRole());

                   List<String> groupList = new ArrayList<>();

                   for (Map<String,Object> functionMap : userFunctionList){
                       groupList.add(functionMap.get("menuName").toString());
                       if(Integer.parseInt(functionMap.get("functionId").toString()) == 72){
                           isPay = true;
                       }
                   }
               }
               if(isPay == false){
                   data.setCodeEnum(CodeEnum.CODE_60024);
                   return data;
               }

               Object userPhone = params.get("userPhone");
               Object check = params.get("check");
               Integer payWay = Integer.parseInt(params.get("payWay").toString());

               Integer payWays = null;
               if(ObjUtils.isNotEmpty(params.get("payWays"))){
                   payWays = Integer.parseInt(params.get("payWays").toString());
               }

               TOrderInfo orderInfo = orderInfoMapper.selectByPrimaryKey(orderId);

               //代付校验
//               if(ObjUtils.isNotEmpty(check) && ObjUtils.isNotEmpty(userPhone)){
               if(ObjUtils.isNotEmpty(userPhone)){
//                   //校验代付验证码
//                   if(!orderInfo.getReplacePayCode().equals(check) || !userPhone.equals(orderInfo.getPayUserPhone())){
//                       data.setCodeEnum(CodeEnum.CODE_10006);
//                       return data;
//                   }
//                   //时间校验
//                   if(orderInfo.getPayCreateTime().getTime() < new Date().getTime()){
//                       data.setCodeEnum(CodeEnum.CODE_10013);
//                       return data;
//                   }
                   //绑定代付人
                   List<TUserInfo> userList = userInfoMapper.selectByMap(params);
                   if(userList.size() > 0){
                       orderInfo.setPayUserId(userList.get(0).getUserId());
                   }
                   payWays = 7;
               }
               if(ObjUtils.isNotEmpty(payWay)){
                   orderInfo.setPayWay(payWay);
               }

               if(ObjUtils.isNotEmpty(payWays)){
                   orderInfo.setPayWays(payWays);
               }

               //判断订单是否存在
               if(ObjUtils.isEmpty(orderInfo)){
                   data.setCodeEnum(CodeEnum.CODE_6);
                   return data;
               }
               //判断订单是否重复提交
               if( orderInfo.getOrderState() == 0){
                   data.setCodeEnum(CodeEnum.CODE_60006);
                   return data;
               }

               //核销优惠券或体验券
               Map<String,Object> couponMap = usedCoupon(orderInfo,data);
               CodeEnum resultMsg = (CodeEnum) couponMap.get("EnumCode");
               // 如果不为空
               if (ObjUtils.isNotEmpty(resultMsg)) {
                   // 设置返回数据
                   data.setCodeEnum(resultMsg);
                   TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                   return data;
               }
               boolean orderStatus = ((Boolean) couponMap.get("flag")).booleanValue();
               // 1满减券  2体验券  3通用券 5次卡
               Integer cardType = Integer.parseInt(couponMap.get("cardType").toString());
               //优惠金额 满减券和通用券使用
               BigDecimal discountCosts = new BigDecimal(couponMap.get("discountCosts").toString());

               //获取销售提成金额
               Map<String,Object> orderCostMap = getOrderCost(params, orderInfo, orderStatus ,cardType, discountCosts, payWay, payWays);

               //订单总金额
               BigDecimal orderSumMoney = new BigDecimal(orderCostMap.get("orderSumMoney").toString());
               //大夫提成金额
               BigDecimal doctorSale = new BigDecimal(orderCostMap.get("doctorSale").toString());
               BigDecimal payMoney = new BigDecimal(orderCostMap.get("payMoney").toString());
               //余额支付金额
               BigDecimal balancePayCost = new BigDecimal(orderCostMap.get("balancePayCost").toString());
               //服务名称
               Object serviceName = orderCostMap.get("serviceName");
               //生成帐户流水
               orderInfo.setBalancePayCost(balancePayCost);

               String userName = userInfoMapper.selectByPrimaryKey(orderInfo.getUserId()).getUserName();

               //余额支付
               if(orderInfo.getPayWay() == 0 || orderInfo.getPayWays() == 7 || orderInfo.getPayWays() == 0){
                   //代付订单 - PayWay = 7
                   //就诊订单 - 余额支付
                   //商品订单 - PayWay = 6 && 代付人不为空
                   //         PayWays = 7 || 0  PayWays是商品订单的支付方式

                   Integer userId = 0;
                   if(ObjUtils.isNotEmpty(orderInfo.getPayUserId())){
                       userId = orderInfo.getPayUserId();
                   }else{
                       userId = orderInfo.getUserId();
                   }
                   params.put("applyUserId", userId);
                   params.put("isBack", 0); // 0未退款 ， 1 已退款

                   List<TBackcardInfo> backcardInfo = backcardInfoMapper.selectByMapList(params);
                   if( backcardInfo.size() > 0 ){
                       data.setCodeEnum(CodeEnum.CODE_60022);
                       return data;
                   }
                   if(orderInfo.getBalancePayCost().doubleValue() > 0){
                       //余额消费
                       TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
                       if( userInfo.getUserAccount().doubleValue() >= orderInfo.getBalancePayCost().doubleValue() ){
                           userInfo.setUserAccount(new BigDecimal(userInfo.getUserAccount().subtract(orderInfo.getBalancePayCost()).doubleValue()));
                           //余额消费扣除本次消费
                           userInfoMapper.updateByPrimaryKeySelective(userInfo);
                       }else{
                           data.setCodeEnum(CodeEnum.CODE_60008);
                           TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                           return data;
                       }
                   }
               }
               saveAccountInfo(orderInfo, cashierId, orderStatus, orderSumMoney, userName, serviceName, doctorSale, payMoney,discountCosts);
           }catch (Exception e){
               data.setCodeEnum(CodeEnum.CODE_1);
               e.printStackTrace();
               TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
           }

       return data;
    }


    /**
     * 核销优惠券或体验券
     * @param orderInfo
     * @param data
     * cardType  // 1满减券  2体验券  3通用券 5次卡
     * @return
     */
    public Map<String,Object> usedCoupon(TOrderInfo orderInfo,ResponseData data){

        Map<String,Object> params = new HashMap<>();
        BigDecimal discountCosts = new BigDecimal(0);
        Integer cardType = 0;
        boolean flag = false;

        //次卡消费
        if(ObjUtils.isNotEmpty(orderInfo.getCardId())){
            cardType = 5;
            params = new HashMap<>();

            String[] cardIds = orderInfo.getCardId().split(",");

            for (String card : cardIds){
                params.put("userId", orderInfo.getUserId());
                params.put("cardId", card);//次卡id
                params.put("validDay", new Date());
                List<TCardUsrRel> cardUsrRel = cardUsrRelMapper.selectByMap(params);
                Integer cardLeftTime = 0;
                for (TCardUsrRel rel : cardUsrRel){
                    //只获取未过期的次卡次数
                    if(rel.getInvalidTime().after(new Date())){
                        cardLeftTime += rel.getCardLeftTime();
                    }
                }

                if(ObjUtils.isEmpty(cardUsrRel)){
                    //次卡不存在
                    params.put("EnumCode",CodeEnum.CODE_60001);
                    return params;
                }
                if(cardLeftTime < 1){
                    //次卡已使用完，请重新购买
                    params.put("EnumCode",CodeEnum.CODE_60002);
                    return params;
                }
                //修改用户次卡剩余次数
                for (TCardUsrRel rel : cardUsrRel){
                    if(rel.getCardLeftTime() >= 1){
                        rel.setCardLeftTime(rel.getCardLeftTime() - 1);
                        cardUsrRelMapper.updateByPrimaryKeySelective(rel);
                        break;
                    }
                }
                flag = true;
                params.put("discountCosts",discountCosts);
                params.put("flag",flag);
                params.put("cardType", cardType);
            }
        }
        //核销优惠券
        if(ObjUtils.isNotEmpty(orderInfo.getCouponId())){
            params.put("flag",flag);
            // 1满减券  2体验券  3通用券
            params.put("userId", orderInfo.getUserId());
            params.put("couponId", orderInfo.getCouponId());
            params.put("isUsed", 0);
            params.put("validDay", 1);
            List<Map<String,Object>> couponList = couponUsrRelMapper.selectByMap(params);
            if(couponList.size() <= 0){
                //优惠券已使用或优惠券不存在
                params.put("EnumCode",CodeEnum.CODE_60003);
                return params;
            }

            for (Map<String,Object> couponMap : couponList){
                //校验该用户券门店限制
                Object cSubclinicIds = couponMap.get("subclinicIds");
                Integer subclinicIds = 0;
                if(ObjUtils.isNotEmpty(cSubclinicIds)) {
                    subclinicIds = Integer.parseInt(cSubclinicIds.toString());
                    if(subclinicIds != 0 && subclinicIds != orderInfo.getSubclinicId()){
                        params.put("EnumCode",CodeEnum.CODE_60007);
                        return params;
                    }
                }
                Date createTime = new Date();
                try {
                    createTime = DateUtils.parse(couponMap.get("useTime").toString());
                    Integer validDay = Integer.parseInt( couponMap.get("validDay").toString());
                    //if(DateUtils.parse(DateUtils.addDay(createTime,validDay),DateUtils.YYYY_MM_DD).getTime() < new Date().getTime()){
                    if(new Date().after(createTime)){
                        params.put("EnumCode",CodeEnum.CODE_60015);
                        return params;
                    }
                } catch (ParseException e) {
                    e.printStackTrace();
                }


                Integer couponType = Integer.parseInt(couponMap.get("cardType").toString());
                //1满减，2体验券，3优惠
                if(couponType != 2){
                    cardType = 3;
                    //满减和优惠券
                    discountCosts = discountCosts.add(new BigDecimal(couponMap.get("discountCosts").toString()));
                    BigDecimal targetCost = new BigDecimal(couponMap.get("targetCost").toString());
                    if(couponType == 1){
                        cardType = 1;
                        //满减券需要满足满 **钱规则
                        //通用券直接减钱
                        if(orderInfo.getOrderPayCost().intValue() <= targetCost.intValue()){
                            //不满足使用条件
                            params.put("EnumCode",CodeEnum.CODE_60005);
                            return params;
                        }
                    }
                }else{
                    cardType = 2;
                    //体验券
                    Integer count = 0;
                    Integer cardId = Integer.parseInt(couponMap.get("cardId").toString());
                    Integer isUsed = Integer.parseInt(couponMap.get("isUsed").toString());
                    if(cardId != orderInfo.getCouponId() || isUsed == 0){
                        params.put("EnumCode",CodeEnum.CODE_60004);
                        return params;
                    }
                    flag = true;
                }
                //销券  更改为已使用
                Integer relId = Integer.parseInt(couponList.get(0).get("relId").toString());
                TCouponUsrRel rel = new TCouponUsrRel();
                rel.setRelId(relId);
                rel.setIsUsed(1);
                rel.setCardType(cardType);
                rel.setUseTime(new Date());
                couponUsrRelMapper.updateByPrimaryKeySelective(rel);
                break;
            }
        }
        params.put("discountCosts",discountCosts);
        params.put("cardType",cardType);
        params.put("flag",flag);
        return params;
    }
    /**
     * 根据订单核算订单金额和大夫提成
     * @param params
     * @param orderInfo
     * @return
     */
    public Map<String,Object> getOrderCost(Map<String,Object> params,TOrderInfo orderInfo, boolean orderStatus, Integer cardType,BigDecimal discountCosts, Integer payWay, Integer payWays){
        Map<String,Object> retOrderMap = new HashMap<>();

        //订单应付金额
        BigDecimal orderMoney = new BigDecimal(0);
        //订单实付金额
        BigDecimal payMoney = new BigDecimal(0);
        //总提成
        BigDecimal saleMoney = new BigDecimal(0);
        //余额支付金额
        BigDecimal balancePayCost = new BigDecimal(0);
        //计算订单总金额
        params.put("orderId", orderInfo.getOrderId());
        List<TOrderGoodsDetail> goodsList = orderGoodsDetailMapper.selectByMap(params);

        //商品订单金额
        BigDecimal goodsMoney = new BigDecimal(0);

        if(goodsList.size() > 0 ){
            for (TOrderGoodsDetail goodsDetail : goodsList){
                goodsMoney = goodsMoney.add(goodsDetail.getGoodsSumCost());
                saleMoney = saleMoney.add(goodsDetail.getGoodsSumIncome());
                payMoney = payMoney.add(goodsDetail.getGoodsSumCost());
            }
            if(payWays == 0 || payWays == 7){
                balancePayCost = balancePayCost.add(goodsMoney);
            }
        }



        List<TOrderServiceDetail> serviceList = orderServiceDetailMapper.selectByMap(params);
        String cardIdStr = orderInfo.getCardId();
        String[] cardIds = null;
        List<Integer> cardServiceIds = new ArrayList<Integer>();
        if (ObjUtils.isNotEmpty(cardIdStr)) {
            cardIds = cardIdStr.split(",");
            for (int i = 0; i < cardIds.length; i++) {
                Integer cardId = Integer.parseInt(cardIds[i]);
                SysAccountCardInfo cardInfo = sysAccountCardInfoMapper.selectByPrimaryKey(cardId);
                cardServiceIds.add(cardInfo.getServiceId());
            }
        }

        //推拿服务订单
        BigDecimal serviceMoney = new BigDecimal(0);
        String serviceName = "";
        if(serviceList.size() > 0 ){
            //推拿一次，大夫提成为25%
            BigDecimal saleRatio = new BigDecimal(0.25);

            for (TOrderServiceDetail serviceDetail : serviceList){

                saleMoney = saleMoney.add(serviceDetail.getServiceCost().multiply(new BigDecimal(saleRatio.doubleValue())));

                if (cardServiceIds.size() > 0 && cardServiceIds.contains(serviceDetail.getServiceId())) {

                } else {
                    serviceMoney = serviceMoney.add(serviceDetail.getServiceCost());
                }

                serviceName = serviceDetail.getServiceName();
                payMoney = payMoney.add(serviceDetail.getServiceCost());
            }
            //判断推拿服务的支付方式
            payWays = payWays == null ? -1 : payWays;
            if(payWay == 0 || payWays == 7){
                balancePayCost = balancePayCost.add(serviceMoney);
            }

            //获取推拿服务
            serviceName = serviceName.substring(0, serviceName.length());
            System.out.println("serviceName = "+ serviceName);
        }


        //当用户使用优惠券或者体验券时，应扣除推拿服务的金额
        if(orderStatus){
            // orderStatus = true 次卡消费
            // cardType = 5 体验券消费
            // discountCosts 优惠金额
            // goodsMoney 商品金额
            // serviceMoney 推拿服务金额
            if( goodsMoney.doubleValue() > discountCosts.doubleValue()){
                orderMoney = orderMoney.add(goodsMoney).subtract(discountCosts);
            }
        }else{
            orderMoney = orderMoney.add(goodsMoney).add(serviceMoney);
            if(orderMoney.doubleValue() > discountCosts.doubleValue()){
                orderMoney = orderMoney.subtract(discountCosts);
            }
        }

        System.out.println("orderMoney = " + orderMoney);

        retOrderMap.put("serviceName",serviceName);//服务名称
        retOrderMap.put("doctorSale",saleMoney.doubleValue());//提成
        retOrderMap.put("payMoney", orderMoney.doubleValue());//订单实付金额
        retOrderMap.put("orderSumMoney", payMoney.doubleValue());//订单应付金额
        retOrderMap.put("balancePayCost", balancePayCost.doubleValue());//订单应付金额
        return retOrderMap;
    }

    /**
     * 生成订单流水
     * @param orderInfo         订单对象
     * @param cashierId         收款人
     * @param orderStatus       订单状态
     * @param orderSumMoney     实付金额
     * @param userName          用户名
     * @param serviceName       服务名称
     * @param doctorSale         大夫提成金额
     * @param payMoney          实付金额
     */
    public void saveAccountInfo(TOrderInfo orderInfo,Integer cashierId,boolean orderStatus,BigDecimal orderSumMoney,
                                String userName,Object serviceName,BigDecimal doctorSale,BigDecimal payMoney,BigDecimal discountCosts){
        Map<String,Object> params = new HashMap<>();
        params.put("bookingId", orderInfo.getBookingId());
        //修改病例状态
        TPatientTreatment patientTreatment = treatmentMapper.selectByMap(params);
        boolean treatmentIsSubmit = ObjUtils.isNotEmpty(patientTreatment) && ObjUtils.isNotEmpty(patientTreatment.getTreatmentImg())
                && ObjUtils.isNotEmpty(patientTreatment.getHandsImg()) && ObjUtils.isNotEmpty(patientTreatment.getFaceImg())
                && ObjUtils.isNotEmpty(patientTreatment.getDiseaseInfo()); // 暂时只判断三张照片是否上传

        TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(orderInfo.getBookingId());

        boolean needCalculateDoctorCost = treatmentIsSubmit || bookingInfo.getBookingType() == 1; // 病历已提交 || 预防保健

        if (needCalculateDoctorCost) {
            patientTreatment.setTreatmentState(1);
            treatmentMapper.updateByPrimaryKeySelective(patientTreatment);

            //大夫提成
            AccountDoctorInfo doctorInfo = new AccountDoctorInfo();
            doctorInfo.setBookingId(orderInfo.getBookingId());
            doctorInfo.setOrderId(orderInfo.getOrderId());
            doctorInfo.setUserName(userName);
            doctorInfo.setDoctorId(orderInfo.getDoctorId());
            doctorInfo.setDetailName(serviceName + "");
            doctorInfo.setOrderPayCost(doctorSale);
            accountDoctorInfoMapper.insertSelective(doctorInfo);
        }

        //订单流水
        AccountOrderInfo accountOrderInfo = new AccountOrderInfo();
        accountOrderInfo.setBookingId(orderInfo.getBookingId());
        accountOrderInfo.setOrderId(orderInfo.getOrderId());
        accountOrderInfo.setCreateTime(new Date());
        accountOrderInfo.setOrderTotalCost(orderSumMoney);
        accountOrderInfo.setOrderPayCost(payMoney);
        accountOrderInfo.setCouponTotalCost(discountCosts);
        accountOrderInfo.setDoctorId(orderInfo.getDoctorId());
        accountOrderInfo.setSubclinicId(orderInfo.getSubclinicId());
        if (null == accountOrderInfoMapper.selectByOrderId(orderInfo.getOrderId())) {
            accountOrderInfoMapper.insertSelective(accountOrderInfo);
        }
        //用户流水
        AccountUserInfo accountUserInfo = new AccountUserInfo();
        accountUserInfo.setOrderId(orderInfo.getOrderId());
        if(ObjUtils.isNotEmpty(orderInfo.getCardId())){
            if(orderInfo.getCardId().indexOf(",") > -1){
                String cardId = orderInfo.getCardId().substring(0,orderInfo.getCardId().indexOf(","));
                accountUserInfo.setCardId(cardId);
            }else{
                accountUserInfo.setCardId(orderInfo.getCardId());
            }
        }
        accountUserInfo.setCashierId(cashierId);
        accountUserInfo.setAccountType(0);
        accountUserInfo.setCardType(orderStatus ? 0 : 1);
        accountUserInfo.setSubclinicId(orderInfo.getSubclinicId());
        accountUserInfo.setUserId(orderInfo.getUserId());
        accountUserInfo.setAccountCost(payMoney);
        if(orderInfo.getPayWay() == 7){
            accountUserInfo.setAccountDesc("代付订单");
        }else if(orderInfo.getPayWay() == 6){
            accountUserInfo.setAccountDesc("商品订单");
        }else{
            accountUserInfo.setAccountDesc("就诊消费");
        }
        accountUserInfo.setBalancePayCost(orderInfo.getBalancePayCost());
        accountUserInfo.setCreateTime(new Date());
        accountUserInfo.setDoctorId(orderInfo.getDoctorId());
        accountUserInfo.setPayWay(orderInfo.getPayWay());
        accountUserInfo.setAccountNo(ObjUtils.getAccountNo());
        accountUserInfoMapper.insertSelective(accountUserInfo);

        if(ObjUtils.isNotEmpty(orderInfo.getPayUserId())){
            accountUserInfo = new AccountUserInfo();
            accountUserInfo.setOrderId(orderInfo.getOrderId());
            accountUserInfo.setCashierId(cashierId);
            accountUserInfo.setAccountType(0);
            accountUserInfo.setCardType(orderStatus ? 0 : 1);
            accountUserInfo.setSubclinicId(orderInfo.getSubclinicId());
            accountUserInfo.setUserId(orderInfo.getPayUserId());
            accountUserInfo.setBalancePayCost(orderInfo.getBalancePayCost());
            accountUserInfo.setAccountCost(payMoney);
            accountUserInfo.setAccountDesc("代付订单");
            accountUserInfo.setCreateTime(new Date());
            accountUserInfo.setDoctorId(orderInfo.getDoctorId());
            accountUserInfo.setPayWay(orderInfo.getPayWay());
            accountUserInfo.setAccountNo(ObjUtils.getAccountNo());
            accountUserInfoMapper.insertSelective(accountUserInfo);
        }

        //修改预约单状态
        if(ObjUtils.isNotEmpty(bookingInfo)){
            bookingInfo.setBookingStatus(4);
            bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);
        }
        //修改订单状态
        orderInfo.setCashierId(cashierId);
        orderInfo.setOrderState(0);
        orderInfo.setPayState(0);
        if (needCalculateDoctorCost) {
            orderInfo.setDoctorCost(doctorSale);
        }
        orderInfo.setOrderTime(new Date());

        //已预约单为主，更新订单共有字段
        if(ObjUtils.isNotEmpty(orderInfo.getBookingId())){
            orderInfo.setDoctorId(bookingInfo.getDoctorId());
            orderInfo.setBookingId(bookingInfo.getBookingId());
            orderInfo.setUserId(bookingInfo.getUserId());
            orderInfo.setPatientId(bookingInfo.getPatientId());
            orderInfo.setSubclinicId(bookingInfo.getSubclinicId());
            orderInfo.setBookingType(bookingInfo.getBookingType());
            orderInfo.setIsAdd(bookingInfo.getIsAdd());
            orderInfo.setDegreeId(bookingInfo.getDegreeId());
        }
        orderInfoMapper.updateByPrimaryKeySelective(orderInfo);
        //新增推送 - 与技师端业务保持一致
        TDoctorPushRel doctorPushRel = new TDoctorPushRel();
        doctorPushRel.setDoctorId(orderInfo.getDoctorId());
        doctorPushRel.setUserId(orderInfo.getUserId());
        doctorPushRel.setPatientId(orderInfo.getPatientId());
        doctorPushRel.setBookingId(orderInfo.getBookingId());
        saveDoctorPush(doctorPushRel,orderInfo);
    }
    public void saveDoctorPush(TDoctorPushRel doctorPushRel,TOrderInfo orderInfo) {

        //消费完成后 - 给用户推送余额和剩余次卡记录

        Integer count = 0;

        Map<String, Object> params = new HashMap<>();
        params.put("patientId", doctorPushRel.getPatientId());
        Map<String, Object> initMap = patientInitMapper.selectByMap(params);

        TPatientInit init = new TPatientInit();
        init.setRelId(Integer.parseInt(initMap.get("relId").toString()));
        init.setTherapyStatus(5);
        patientInitMapper.updateByPrimaryKeySelective(init);

        doctorPushRelMapper.insertSelective(doctorPushRel);

        if(ObjUtils.isNotEmpty(orderInfo.getPayUserId())){
            //给代付人发信息
            TUserInfo payUserInfo = userInfoMapper.selectByPrimaryKey(orderInfo.getPayUserId());
            TUserInfo orderUserInfo = userInfoMapper.selectByPrimaryKey(orderInfo.getUserId());
            if(ObjUtils.isNotEmpty(payUserInfo.getOpenId())){
                Map<String, String> param = new HashMap<>();
                param.put("openId", payUserInfo.getOpenId());
                param.put("otherName", orderUserInfo.getUserName());
                param.put("payCount", String.valueOf(orderInfo.getOrderPayCost()));
                param.put("payTime", DateUtils.format(orderInfo.getOrderTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
                String str = HttpUtils.submitPostData("http://wechat.xrtn.dmpp.net.cn/children/frontend/web/index.php?r=wechat/sendpayothersuccess", param,"utf-8");
                System.out.println("str = " + str);
            }
        }

        if(ObjUtils.isNotEmpty(orderInfo.getUserId())){
            //消费提醒
            TUserInfo userInfo = userInfoMapper.selectByPrimaryKey(orderInfo.getUserId());
            if(ObjUtils.isNotEmpty(userInfo.getOpenId())){
                Map<String, String> param = new HashMap<>();
                param.put("openId", userInfo.getOpenId());
                param.put("orderNo", orderInfo.getOrderNo());
                param.put("payCount", String.valueOf(orderInfo.getOrderPayCost()));
                param.put("payTime", DateUtils.format(orderInfo.getOrderTime(),DateUtils.YYYY_MM_DD_HH_MM_SS));
                String str = HttpUtils.submitPostData("http://wechat.xrtn.dmpp.net.cn/children/frontend/web/index.php?r=wechat/sendorderpaysuccess", param,"utf-8");
                System.out.println("str = " + str);
            }
        }

    }

    @Override
    public Integer updateOrderDoctor(Integer orderId, Integer doctorId, Integer doctorSubId) {
        // 修改订单信息
        TOrderInfo updateOrder = orderInfoMapper.selectByPrimaryKey(orderId);
        if (updateOrder.getDoctorId().intValue() == doctorId.intValue()) {
            return -1; // 修改大夫与原订单大夫一致
        }
        if (updateOrder.getOrderState() != 0) {
            return -2; // 订单未完成，无法修改推拿师
        }
        if (updateOrder.getSubclinicId() != doctorSubId) {
            return -3; // 暂不允许跨店转移订单
        }
        updateOrder.setDoctorId(doctorId);
        orderInfoMapper.updateByPrimaryKeySelective(updateOrder);

        // 修改订单流水
        AccountOrderInfo accountOrderInfo = accountOrderInfoMapper.selectByOrderId(orderId);
        accountOrderInfo.setDoctorId(doctorId);
        accountOrderInfoMapper.updateByPrimaryKeySelective(accountOrderInfo);

        // 修改医生提成
        AccountDoctorInfo accountDoctorInfo = accountDoctorInfoMapper.selectByOrderId(orderId);
        if (ObjUtils.isNotEmpty(accountDoctorInfo)) {
            accountDoctorInfo.setDoctorId(doctorId);
            accountDoctorInfoMapper.updateByPrimaryKeySelective(accountDoctorInfo);
        }

        // 修改预约
        Integer bookingId = updateOrder.getBookingId();
        if (ObjUtils.isNotEmpty(bookingId)) {
            TBookingInfo bookingInfo = bookingInfoMapper.selectByPrimaryKey(bookingId);
            bookingInfo.setDoctorId(doctorId);
            bookingInfoMapper.updateByPrimaryKeySelective(bookingInfo);
        }

        // 修改订单服务信息
        Map<String, Object> params = new HashMap<>();
        params.put("orderId", orderId);
        List<TOrderServiceDetail> serviceDetails = orderServiceDetailMapper.selectByMap(params);
        for (TOrderServiceDetail serviceDetail : serviceDetails) {
            TOrderServiceDetail updateService = new TOrderServiceDetail();
            updateService.setRelId(serviceDetail.getRelId());
            updateService.setDoctorId(doctorId);
            orderServiceDetailMapper.updateByPrimaryKeySelective(updateService);
        }

        // 修改订单商品信息
        List<TOrderGoodsDetail> goodsDetails = orderGoodsDetailMapper.selectByMap(params);
        for (TOrderGoodsDetail goodsDetail : goodsDetails) {
            TOrderGoodsDetail updateGoods = new TOrderGoodsDetail();
            updateGoods.setRelId(goodsDetail.getRelId());
            updateGoods.setDoctorId(doctorId);
            orderGoodsDetailMapper.updateByPrimaryKeySelective(updateGoods);
        }

        return 1;
    }

    @Override
    public Integer updateAccountUserInfoDoctor(Integer orderId, Integer doctorId, Integer doctorSubId) {
        AccountUserInfo updateAccount = accountUserInfoMapper.selectByPrimaryKey(orderId);
        if (updateAccount == null) {
            return -2; // 卡项订单不存在
        }
        if (updateAccount.getCashierId().intValue() == doctorId.intValue()) {
            return -1; // 修改大夫与原订单大夫一致
        }
        if (updateAccount.getSubclinicId() != doctorSubId) {
            return -3; // 暂不允许跨店转移订单
        }
        updateAccount.setCashierId(doctorId);
        updateAccount.setSubclinicId(doctorSubId);
        accountUserInfoMapper.updateByPrimaryKeySelective(updateAccount);
        return 1;
    }
}
